package com.hdmp.libiary.controller;

import com.hdmp.libiary.configuration.Properties;
import com.hdmp.tool.bean.ResultBean;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Author: Chenyc
 * @Date: 2019/6/9 10:05
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    @Autowired
    Properties properties;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultBean uploadImage(@RequestParam(value = "file")MultipartFile file) throws Exception{
        if(file.isEmpty()){
            return new ResultBean("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        System.out.println("文件名：：："+fileName);
        String filePath = properties.getUploadDir();
        String path = java.util.UUID.randomUUID()+fileName.substring(fileName.indexOf("."));
        File newfile = new File(filePath+path);
        System.out.println(newfile);
        if(!newfile.getParentFile().exists()){
            System.out.println("文件目录不存在！！，自动新建");
            newfile.getParentFile().mkdirs();
        }
        try{
            file.transferTo(newfile);
            return new ResultBean(path);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResultBean("上传失败");
    }

    //在线展示
    @RequestMapping(value = "/{filename}", method = RequestMethod.GET)
    public void downloadImage(@PathVariable String filename, String type, HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("the imageName is : "+filename);
        String fileUrl = properties.getUploadDir()+filename;
        if (fileUrl != null) {
            //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
           /* String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");*/
            /*File file = new File(realPath, fileName);*/
            File file = new File(fileUrl);
            if (file.exists()) {
                if("down".equals(type)){
                    response.setHeader("content-type", "application/octet-stream");
                    response.setContentType("application/octet-stream");
                    // 下载文件能正常显示中文
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                }else{
                    response.setContentType("image/png");
                    response.addHeader("Content-Disposition","inline;fileName=" + filename);
                }

                byte[] buffer = new byte[8192];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = 0;
                    while ((i =  bis.read(buffer)) != -1) {
                        os.write(buffer, 0, i);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}